<template>
  <div>
    <div style="margin: 10px 0">
      <el-input style="width: 200px" placeholder="Please enter name" suffix-icon="el-icon-search" v-model="name"></el-input>
<!--      <el-input style="width: 200px" placeholder="请输入" suffix-icon="el-icon-message" class="ml-5" v-model="email"></el-input>-->
<!--      <el-input style="width: 200px" placeholder="请输入" suffix-icon="el-icon-position" class="ml-5" v-model="address"></el-input>-->
      <el-button class="ml-5" type="primary" @click="load">Search</el-button>
      <el-button type="warning" @click="reset">Reset</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAdd">Add <i class="el-icon-circle-plus-outline"></i></el-button>

      <el-popconfirm
          class="ml-5"
          confirm-button-text='determine'
          cancel-button-text='Let me think again'
          icon="el-icon-info"
          icon-color="red"
          title="Are you sure to delete this data in bulk？"
          @confirm="delBatch"
      >
        <el-button type="danger" slot="reference">Batch deletion <i class="el-icon-remove-outline"></i></el-button>
      </el-popconfirm>
      <!-- <el-upload action="http://localhost:9090/paper/import" :show-file-list="false" accept="xlsx" :on-success="handleExcelImportSuccess" style="display: inline-block">
        <el-button type="primary" class="ml-5">导入 <i class="el-icon-bottom"></i></el-button>
      </el-upload>
      <el-button type="primary" @click="exp" class="ml-5">导出 <i class="el-icon-top"></i></el-button> -->
    </div>

    <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="60" sortable></el-table-column>
      <el-table-column prop="name" label="Paper name" width="120"></el-table-column>
      <el-table-column prop="score" label="Total score" width="150"></el-table-column>
      <el-table-column prop="duration" label="Duration (minutes)"></el-table-column>
      <el-table-column label="Affiliated course">
        <template v-slot="scope">
          <span v-if="courses && courses.length">{{ courses.find(v => v.id === scope.row.courseId).name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="Examination paper">
        <template v-slot="scope">
          <el-button type="primary" @click="viewPaper(scope.row.id)">View the examination paper</el-button>
        </template>
      </el-table-column>
      <el-table-column label="Operation"  width="400" align="center">
        <template slot-scope="scope">
          <el-button type="primary" plain @click="handlePaper(scope.row.id, scope.row.courseId)">Manual volume grouping <i class="el-icon-document"></i></el-button>
          <el-button type="primary" @click="takePaper(scope.row.id, scope.row.courseId)">Automatic paper grouping <i class="el-icon-document"></i></el-button>

          <el-button type="success" @click="handleEdit(scope.row)">Edit <i class="el-icon-edit"></i></el-button>
          <el-popconfirm
              class="ml-5"
              confirm-button-text='Yes'
              cancel-button-text='Let me see'
              icon="el-icon-info"
              icon-color="red"
              title="Are you sure about deleting it？"
              @confirm="del(scope.row.id)"
          >
            <el-button type="danger" slot="reference">Delete <i class="el-icon-remove-outline"></i></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="手动组卷" :visible.sync="dialogFormVisible3" width="55%" :close-on-click-modal="false">
      <div style="width: 90%; padding-left: 120px">
        <el-transfer  :titles="['Question bank', 'selected']" filter-placeholder="Please enter type：1 Choice, 2 judgment, 3 question and answer"  filterable :filter-method="filterMethod"
                     v-model="form2.handleQuestionIds" :data="paperQuestions"  :props="{key: 'id',label: 'name'}"></el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible3 = false">cancel</el-button>
        <el-button type="primary" @click="generateHandPaper">confirm</el-button>
      </div>
    </el-dialog>

    <el-dialog title="Examination paper" :visible.sync="dialogFormVisible2" width="60%" :close-on-click-modal="false">
      <el-card>
        <div v-for="(item, index) in questiones" :key="item.id"  style="margin: 20px 0">
          <div style="margin: 10px 0; font-size: 20px"><span>{{ index+1 }}.</span> {{ item.name }}
            <span style="font-size: 14px" v-if="item.type === 1">（Choice）</span>
            <span style="font-size: 14px"  v-if="item.type === 2">（judgment）</span>
            <span style="font-size: 14px"  v-if="item.type === 3">（question and answer）</span>
          </div>
          <div v-if="item.type === 1" style="margin: 10px">
            <span style="margin-right: 20px">A. {{ item.a }}</span>
            <span  style="margin-right: 20px">B. {{ item.b }}</span>
            <span  style="margin-right: 20px">C. {{ item.c }}</span>
            <span  style="margin-right: 20px">D. {{ item.d }}</span>
          </div>
          <div style="margin: 10px">
            Answer： {{ item.answer }}
          </div>
          <div style="margin: 10px">
            Analysis： {{ item.detail }}
          </div>
        </div>
      </el-card>
    </el-dialog>

    <el-dialog title="test paper composition" :visible.sync="dialogFormVisible1" width="30%" :close-on-click-modal="false">
     <el-form label-width="100px" size="small" style="width: 90%">
       <el-form-item label="Number of Choice questions">
         <el-input v-model="form1.type1" autocomplete="off"></el-input>
       </el-form-item>
       <el-form-item label="Number of fill in the blanks">
         <el-input v-model="form1.type2" autocomplete="off"></el-input>
       </el-form-item>
       <el-form-item label="Number of question and answer">
         <el-input v-model="form1.type3" autocomplete="off"></el-input>
       </el-form-item>
     </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">Cancel</el-button>
        <el-button type="primary" @click="generatePaper">Confirm</el-button>
      </div>
    </el-dialog>



    <el-dialog title="Information" :visible.sync="dialogFormVisible" width="30%" :close-on-click-modal="false">
      <el-form label-width="100px" size="small" style="width: 90%">
        <el-form-item label="Name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="Course">
          <el-select clearable v-model="form.courseId" placeholder="Please select" style="width: 100%">
            <el-option v-for="item in courses"
                       :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Duration (minutes)">
          <el-input v-model="form.duration" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="save">Confirm</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Paper",
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      name: "",
      form: {},
      form1: {},
      form2: {},
      dialogFormVisible: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      multipleSelection: [],
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      courses: [],
      questiones: [],
      courseId: null,
      type: null,
      paperQuestions: [],
      // paperQuestionsOrigin: []
    }
  },
  created() {
    this.load()

  },
  methods: {
    filterMethod(query, item) {
      return !query || query == item.type;
    },
    // selectQuestion() {
    //   // Filtering through the original backup data
    //   this.paperQuestions = this.paperQuestionsOrigin.filter(v => v.type === this.type)
    // },
    handlePaper(paperId, courseId) {
      this.request.get("/question").then(res => {
        this.paperQuestions = res.data.filter(v => v.courseId === courseId)
        // console.log(this.paperQuestions)
        // Backup raw data
        // this.paperQuestionsOrigin = JSON.parse(JSON.stringify(this.paperQuestions))
        // this.type = null
      })

      this.form2 = {handleQuestionIds: [], paperId: paperId}
      this.dialogFormVisible3 = true
    },
    viewPaper(paperId) {
      this.request.get("/paper/view/" + paperId).then(res => {
        this.questiones = res.data
        this.dialogFormVisible2 = true
      })
    },
    takePaper(paperId, courseId) {
      this.form1 = {type1: 4, type2: 4, type3: 2, paperId: paperId, courseId: courseId}
      this.dialogFormVisible1 = true
    },
    load() {
      this.request.get("/paper/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })

      this.request.get("/course").then(res => {
        this.courses = res.data
      })
    },
    generatePaper() {
      this.request.post("/paper/takePaper", this.form1).then(res => {
        if (res.code === '200') {
          this.$message.success("Successful composition of examination papers")
          this.dialogFormVisible1 = false
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    generateHandPaper() {
      this.request.post("/paper/handPaper", this.form2).then(res => {
        if (res.code === '200') {
          this.$message.success("Successful composition of examination papers")
          this.dialogFormVisible3 = false
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    save() {
      this.request.post("/paper", this.form).then(res => {
        if (res.code === '200') {
          this.$message.success("Save successfully")
          this.dialogFormVisible = false
          this.load()
        } else {
          this.$message.error("Fail to save")
        }
      })
    },
    handleAdd() {
      this.dialogFormVisible = true
      this.form = {}
      this.$nextTick(() => {
        if(this.$refs.img) {
           this.$refs.img.clearFiles();
         }
         if(this.$refs.file) {
          this.$refs.file.clearFiles();
         }
      })
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogFormVisible = true
       this.$nextTick(() => {
         if(this.$refs.img) {
           this.$refs.img.clearFiles();
         }
         if(this.$refs.file) {
          this.$refs.file.clearFiles();
         }
       })
    },
    del(id) {
      this.request.delete("/paper/" + id).then(res => {
        if (res.code === '200') {
          this.$message.success("Deleted successfully")
          this.load()
        } else {
          this.$message.error("Fail to delete")
        }
      })
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    delBatch() {
      if (!this.multipleSelection.length) {
        this.$message.error("Select the data you want to delete")
        return
      }
      let ids = this.multipleSelection.map(v => v.id)  // [{}, {}, {}] => [1,2,3]
      this.request.post("/paper/del/batch", ids).then(res => {
        if (res.code === '200') {
          this.$message.success("Batch deletion succeeded")
          this.load()
        } else {
          this.$message.error("Fail to Batch deletion")
        }
      })
    },
    reset() {
      this.name = ""
      this.load()
    },
    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum)
      this.pageNum = pageNum
      this.load()
    },
    handleFileUploadSuccess(res) {
      this.form.file = res
    },
    handleImgUploadSuccess(res) {
      this.form.img = res
    },
    download(url) {
      window.open(url)
    },
    exp() {
      window.open("http://localhost:9090/paper/export")
    },
    handleExcelImportSuccess() {
      this.$message.success("Import successfully")
      this.load()
    }
  }
}
</script>


<style>
.headerBg {
  background: #eee!important;
}
</style>
